<template>
	<!-- <div>
    <el-input v-model="url" type="text" style="width: 20%" /> &nbsp; &nbsp;
    <el-button @click="join" type="primary">连接</el-button>
    <el-button @click="exit" type="danger">断开</el-button>

    <br />
    <el-input type="textarea" v-model="message" :rows="9" />
    <el-button type="primary" @click="send">发送消息</el-button>
    <br />
    <br />
    <el-input type="textarea" v-model="text_content" :rows="9" /> 返回内容
    <br />
    <br />
  </div> -->
</template>

<script>
  import { getToken } from "@/utils/auth";
	export default {
		name: "socket",
		props: {
			url: {
				type: String,
				default: "ws://127.0.0.1:8080/websocket"
			},
			message: {
				type: String,
				default: ""
			}
		},
		data() {
			return {
				text_content: "",
				ws: null,
        token: getToken()
			};
		},
		created() {
			this.join()
		},
		methods: {
			join() {
				this.ws = new WebSocket('ws://127.0.0.1:8080/websocket', [this.token]);
				const self = this;
				this.ws.onopen = function(event) {
					self.text_content = "已经打开连接:" + self.url + "\n";
					console.log(self.text_content)
				};
				this.ws.onmessage = function(event) {
					self.text_content = event.data + "\n";
					// console.log(self.text_content)
					if (self.text_content.indexOf('连接成功') == -1) {
						self.$emit("getCallBackSocket", JSON.parse(self.text_content));
					}

				};
				this.ws.onclose = function(event) {
					self.text_content = self.text_content + "已经关闭连接!" + "\n";
					console.log(self.text_content)
				};
        this.ws.onerror = function(event) {
                self.text_content = "连接发生错误";
                console.log(self.text_content);
            };
			},
			exit() {
				if (this.ws) {
					this.ws.close();
					this.ws = null;
				}
			},
			send() {
				if (this.ws) {
					this.ws.send(this.message);
				} else {
					console.log("未连接到服务器")
				}
			},
		},
	};
</script>
